<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
/********************
 *@param function:OplusCms 前臺 頁面管理
 *@param datetime 2012-01-05
 *@param author solgh
 ********************/
require APPPATH.'/libraries/REST_Controller.php';
class Homepage extends REST_Controller{
    public $data=array();
    public function __construct(){
        parent::__construct();
        $this->load->model('admins_mdl');
        $this->load->model('categorys_mdl');
        $this->load->model('products_mdl');
        $this->load->model('orders_mdl');
        $this->load->model('ordersproduct_mdl');
        $this->load->model('specs_mdl');
    }
    /*验证登录*/
    public function checkLogin(){
        $token = $this->input->get_post('token');
        if(!isset($token) || empty($token)){
            $this->response(array('error' => 'Token验证失败','status'=>0), 200);
        }
        $user = $this->admins_mdl->get_admins_by_token($token);
        if(!$user){
            $this->response(array('error' => 'Token验证失败','status'=>0), 200);
        }

    }
    /*登录*/
    public function login_get(){
        $username = $this->input->get_post('username');
        $password = $this->input->get_post('password');
        $query = $this->admins_mdl->get_user_admin($username,md5($password));
        if ($query) {
            $token = md5(time().$query['id']);
            $account = $this->admins_mdl->edit_admins(array('token' => $token), $query['id']);
            $user = array();
            if($account){
                $user = array(
                    'username' => $query['login_name'],
                    'token' => $token
                );
            }
            $this->response(array('data'=>$user,"status"=>1), 200);
        }
        $this->response(array('error' => '用户名或者密码错误','status'=>0), 200);
    }
    /*轮播图*/
    public function banner_get(){
        $this->load->model('advertisings_mdl');
        $map['status'] = 1;
        $result = $this->advertisings_mdl->get_banner($map);
        if($result){
            $data = array();
            foreach($result as $k=>$list){
                $data[$k]['id'] = $list['id'];
                $data[$k]['title'] = $list['title'];
                $data[$k]['images'] = base_url($list['images']);
                $data[$k]['youtube'] = $list['youtube'];
            }
            $this->response(array('data'=>$data,"status"=>1), 200);
        }
        $this->response(array('error' => 'error','status'=>0), 200);
    }
    /*商品分类*/
    public function categorys_get(){
        $language = (int)$this->input->get_post('language');
        $map = array('language_id'=>$language,'status'=>1,'parent_id'=>0);
        $result = $this->categorys_mdl->getCategories($map);
        $data = array();
        if($result){
            foreach($result as $k=>$list){
                $data[$k]['id'] = $list['id'];
                $data[$k]['title'] = $list['title'];
                if(!empty($list['main_image'])){
                    $data[$k]['main_image'] = base_url($list['main_image']);
                }else{
                    $data[$k]['main_image'] = '';
                }
                if(!empty($list['main_image'])){
                    $data[$k]['main_icon'] = base_url($list['main_icon']);
                }else{
                    $data[$k]['main_icon'] = '';
                }
            }
            $this->response(array('data'=>$data,"status"=>1), 200);
        }
        $this->response(array('error' => 'error','status'=>0), 200);
    }
    /*搜索商品*/
    public function search_get(){
        $page = $this->input->get_post('page');
        $page = (!empty($page) && is_numeric($page)) ? intval($page) : 1;
        $limit = 8;
        $offset = ($page - 1) * $limit;
        $category_id = (int)$this->input->get_post('category_id');
        if(!empty($category_id) && !$this->categorys_mdl->get_categorys_by_id($category_id)){
            $this->response(array('error' => '该分类不存在','status'=>0), 200);
        }
        $keyword = $this->input->get_post('keyword');
        $language = (int)$this->input->get_post('language');
        $map['language_id'] = $language;
        $map['status'] = 1;
        $map['field'] = 'n.sort_order ASC,n.add_time';
        $map['sort'] = 'desc';
        $map['limits'] = $limit;
        $map['offset'] = $offset;
        $map['category_id'] = $category_id;
        if(!empty($keyword)){
            $map['title'] = $keyword;
            $map['number'] = $keyword;
        }
        $products_lists=$this->products_mdl->get_products($map);
        if($products_lists && $products_lists->num_rows()>0){
            $products = $products_lists->result_array();
            foreach($products as $k=>$v){
                if($v['is_spec']==1){
                    $products[$k]['is_spec'] = base_url('/themes/front/img/icon-new.png');
                }else{
                    $products[$k]['is_spec'] = base_url('/themes/front/img/icon-hot.png');
                }
                if(empty($v['main_image'])){
                    $products[$k]['main_image'] = base_url('themes/front/img/no-image.png');
                }else{
                    $products[$k]['main_image'] = base_url($v['main_image']);
                }
            }
            $this->response(array('data'=>$products,"status"=>1), 200);
        }
        $this->response(array('error' => 'error','status'=>0), 200);

    }
    /*商品属性列表*/
    public function productSpec_get(){
        $product_id = (int)$this->input->get_post('product_id');
        $language = (int)$this->input->get_post('language');
        if(!$this->products_mdl->get_products_by_id($product_id)){
            $this->response(array('error' => '商品不存在或已被删除','status'=>0), 200);
        }
        $row = redCache("spec_items_".$product_id);
        if($row){
            $defaultItem = $row['defaultItem'];
//            $itemPriceOne = $this->products_mdl->getProductItemPriceOne(array('spec_key'=>$defaultItem,'product_id'=>$product_id));
//            $defaultPrice = (float)$itemPriceOne['price'];
            $specList = $row['specList'];
            uasort($specList, "sort_spec");
            $data = array();
            $data['product_id'] = $row['id'];
            $data['title'] = $row['name'];
            $data['price'] = format_free($row['price']);
            $data['specList'] = [];
            if($row['specList']){
                foreach ($row['specList'] as $spec_id => $spec) {
                    $spec['spec_id'] = $spec_id;
                    $items = array();
                    foreach($spec['items'] as $item_id=>$item){
                        $item['item_id'] = $item_id;
                        $items[] = $item;
                    }
                    $spec['items'] = $items;
                    $data['specList'][] = $spec;
                }
            }
            $this->response(array('data'=>$data,"status"=>1), 200);
        }else{
            $this->response(array('error' => '该商品属性不存在!','status'=>0), 200);
        }
    }

    /*商品详情*/
    public function detail_get(){
        $product_id = (int)$this->input->get_post('product_id');
        $language = (int)$this->input->get_post('language');
        $product = $this->products_mdl->get_products_by_id($product_id);
        $row = $this->products_mdl->get_descriptions($product_id,$language);
        $result = $row->row_array();
        $img[] = $product['main_image'];
        if(!empty($product['photo'])){
            $photo = unserialize($product['photo']);
            if(is_array($photo) && count($photo) > 0){
                $img = array_merge($img,$photo);
            }
        }
        if($product && $result){
            $data['product_id'] = $product['id'];
            $data['title'] = $result['title'];
            $data['photo'] = base_url(implode(',',$img));
            if($product['stock']>0 && $language==1){
                $data['stock'] = '有庫存';
            }else if($product['stock']<0 && $language==2){
                $data['stock'] = 'No inventory';
            }else if($product['stock']>0 && $language==2){
                $data['stock'] = 'In stock';
            }else{
                $data['stock'] = '無庫存';
            }
            $data['old_price'] = 'HK$'.$product['old_price'];
            $data['price'] = 'HK$'.$product['price'];
            $data['logo'] = base_url($this->_get_logo('home'));
            $data['content'] = $result['content'];
            $this->response(array('data'=>$data,"status"=>1), 200);
        }
        $this->response(array('error' => 'error','status'=>0), 200);
    }
    //獲取logo圖片
    private function _get_logo($var='home'){
        if(!empty($var)){
            $this->load->model('logoimg_mdl');
            $filter=array('status'=>1);
             $logo =  $this->logoimg_mdl->get_logoimg($filter)->row_array();
             return $logo['logo'];
        }
    }
    /*搜索订单号*/
    public function orderQuery_get(){
        $invoice_no = $this->input->get_post('invoice_no');
        $language = (int)$this->input->get_post('language');
        $order = $this->orders_mdl->get_one_order(array('invoice_no'=>$invoice_no));
        $products=$this->ordersproduct_mdl->get_ordersproduct(array('order_id'=>$order['id']));
        $pdata = array();
        if(!empty($products) && $products->num_rows()>0){
            foreach ($products->result_array() as $k=> $list){
                $thumb_img=!empty($list['color']) && file_exists($list['color'])?base_url(Imagelib::resize_thumb($list['color'],100,57,FALSE)):base_url('themes/front/img/no-image.png');
                $large_image=!empty($list['color']) && file_exists($list['color'])?base_url(Imagelib::resize_thumb($list['color'],800,450,FALSE)):base_url('themes/front/img/no-image-large.png');
                $attrStr = '';
                $attrprice = 0;
                if(!empty($list['attrs'])){
                    $attrArr = unserialize($list['attrs']);
                    if($attrArr){
                        foreach($attrArr as $attr){
                            $attrStr .= $attr['name'].$attr['num'].' 份 ';
                            $attrprice += $attr['price'];
                        }
                    }
                }
                $list['price'] += $attrprice;
                $pdata[$k]['product_id'] = $list['id'];
                $pdata[$k]['name'] = $list['name'].'';
                $pdata[$k]['specs'] = $attrStr;
                $pdata[$k]['price'] = '$'.$list['price'].'/'.$list['model'];
                $pdata[$k]['thumb_img'] = $thumb_img;
                $pdata[$k]['large_image'] = $large_image;
                $pdata[$k]['quantity'] = $list['quantity'];
            }
        }
        if($order && $products){
            $data['order_id'] = $order['id'];
            $data['invoice_no'] = $order['invoice_no'];
            $data['total'] = '$'.$order['total'];
            $data['product_num'] = $order['product_num'];
            $data['products'] = $pdata;
            $this->response(array('data'=>$data,"status"=>1), 200);
        }
        $this->response(array('error' => '請輸入正確的訂單號','status'=>0), 200);
    }
    /*主页文章*/
    public function article_get(){
        $this->load->model('pages_mdl');
        $article_id = (int)$this->input->get_post('article_id');
        $language = (int)$this->input->get_post('language');
        if(!$this->pages_mdl->get_pages_by_id($article_id)){
            $this->response(array('error' => '該文章不存在或已被刪除','status'=>0), 200);
        }
        $lists = $this->get_list();
        foreach($lists as $key=>$arr){
            foreach($arr as $v){
                if($v['key']=='title' && $language==1) {
                    $this->data['copyright'] = $v['value'];
                }
                if($v['key']=='entitle' && $language==2){
                    $this->data['copyright'] = $v['value'];
                }
            }

        }
        $map['status'] = 1;
        $map['id'] = $article_id;
        $map['language_id'] = $language;
        $this->data['page_list'] = $this->pages_mdl->get_pages_by_unique_url($map);
        $this->load->view('page_view',$this->data);
    }
     //獲取基本設置
    public function get_list(){
        $this->load->model('settings_mdl');
        $query=$this->settings_mdl->get_settings();
        $sdata=array();
        foreach($query->result_array() as $q){
            $sdata[$q['group']][]=array(
                'key'=>$q['key'],
                'value'=>$q['value'],
                'description'=>$q['description']);
        }
        $lists = $sdata;
        return $lists;
    }
    /*显示购物车内容*/
    public function getOrderSpecs_get(){
        $getOrder = $this->input->get_post('cart_data');
        $orderArray = htmlspecialchars_decode($getOrder);
        $cart_data = json_decode($orderArray,true);
        if(!isset($cart_data) || empty($cart_data)){
            $this->response(array('error' => '參數錯誤!','status'=>0), 200);
        }
        $base = array();
        $num = 0;
        $total = 0;
        if(!empty($cart_data)) {
            foreach ($cart_data as $k => $cart) {
                $result = $this->products_mdl->get_products_by_unique_url(array('id' => $cart['id']));
                if (isset($cart) && is_array($cart)) {
                    $base[$k]['product_id'] = $result['id'];
                    $base[$k]['pname'] = $result['title'];
                    $base[$k]['unit'] = $result['unit'];
                    if (!empty($result['main_image'])) {
                        $base[$k]['main_image'] = base_url($result['main_image']);
                    } else {
                        $base[$k]['main_image'] = base_url('themes/front/img/no-image.png');
                    }
                    $spec_arr = explode('_', $cart['key']);
                    sort($spec_arr);
                    $spec_key = implode("_", $spec_arr);
                    $arrePrice = $this->products_mdl->getSpecItemPrice($spec_key);
                    if ($arrePrice != 0) {
                        $result['price'] += $arrePrice;
                    }
                    $name = $this->products_mdl->getSpecItemName($spec_key);
                    $base[$k]['title'] = $result['title'] . " " . $name;
                    $base[$k]['spec'] = $spec_key;
                    $base[$k]['num'] = (int)$cart['num'];
                    $base[$k]['price'] = format_free($result['price']);
                    $num += (int)$cart['num'];
                    $base[$k]['attrArr'] = array();
                    if (isset($cart['attrs']) && !empty($cart['attrs'])) {
                        $attrArr = $cart['attrs'];
                        $attrItems = $this->specs_mdl->_get_itemsBYIds(array_keys($attrArr), '');
                        if ($attrItems) {
                            foreach ($attrItems as $attr) {
                                $attr['num'] = $attrArr[$attr['id']];
                                $base[$k]['attrArr'][] = $attr;
                                $result['price'] += $attrArr[$attr['id']] > 0 ? $attrArr[$attr['id']] * $attr['price'] : 0;
                            }
                        }
                    }
                    $total += $result['price'] * $cart['num'];

                } else {
                    $base[$k]['attrArr'] = array();
                    $base[$k]['num'] = (int)$cart['num'];
                    $num += $cart['num'];
                    $total += $result['price'] * $cart['num'];
                    $base[$k]['spec'] = 0;
                }
            }
        }

        $data = array('num'=>$num,'total'=>format_free($total),'data'=>$base);
        $this->response(array('data'=>$data,"status"=>1), 200);
    }
//    /*显示购物车内容*/
//    public function getOrderSpecs_get(){
//        $getOrder = $this->input->get_post('cart_data');
//        $orderArray = htmlspecialchars_decode($getOrder);
//        $order = json_decode($orderArray,true);
//        if(!isset($order) || empty($order)){
//            $this->response(array('error' => '參數錯誤!','status'=>0), 200);
//        }
//        $base = array();
//        $num = 0;
//        $total = 0;
//        if(!empty($order)){
//            $product_ids = array_keys($order);
//            $query = $this->products_mdl->get_products(array('product_ids'=>$product_ids));
//            $result = $query->result_array();
//            if($result){
//                foreach($result as $i=>$item){
//                    $title = $item['title'];
//                    $item['pname'] = $title;
//                    if(!empty($item['main_image'])){
//                        $item['main_image'] = base_url($item['main_image']);
//                    }else{
//                        $item['main_image'] = base_url('themes/front/img/no-image.png');
//                    }
//                    if(isset($order[$item['id']]) && is_array($order[$item['id']])){
//                        $spec_arr = explode('_',$order[$item['id']]['spec_key']);
//                        sort($spec_arr);
//                        $spec_key = implode("_", $spec_arr);
//                        $name = $this->products_mdl->getSpecItemName($spec_key);
//                        $item['title'] = $title." ".$name;
//                        $item['spec'] =  $spec_key;
//                        $item['num'] = (int)$order[$item['id']]['num'];
//                        $num += (int)$order[$item['id']]['num'];
//                        $item['attrArr'] = null;
//                        $arrePrice = $this->products_mdl->getSpecItemPrice($spec_key);
//                        if($arrePrice!=0){
//                            $item['price'] += $arrePrice;
//                        }
//                        if(isset($order[$item['id']]['attrs']) && !empty($order[$item['id']]['attrs'])){
//                            $attrArr = $order[$item['id']]['attrs'];
//                            $attrItems = $this->specs_mdl->_get_itemsBYIds(array_keys($attrArr),'');
//                            if($attrItems){
//                                foreach($attrItems as $attr){
//                                    $attr['num'] = $attrArr[$attr['id']];
//                                    $item['attrArr'][] =$attr;
//                                    $item['price'] += $attrArr[$attr['id']] > 0 ? $attrArr[$attr['id']]*$attr['price'] : 0;
//                                }
//                            }
//                        }
//                        $total += $item['price']*$order[$item['id']]['num'];
//                        $base[] = $item;
//                    }else{
//                        $item['attrArr'] = null;
//                        $item['num'] = (int)$order[$item['id']];
//                        $num += $order[$item['id']]['num'];
//                        $total += $item['price']*$order[$item['id']]['num'];
//                        $item['spec'] =  0;
//                        $base[] = $item;
//                    }
//                }
//
//            }
//        }
//        $data = array('num'=>$num,'total'=>format_free($total),'data'=>$base);
//        $this->response(array('data'=>$data,"status"=>1), 200);
//
//    }
    /*客户下单*/
    public function order_get(){
        $this->checkLogin();
        $order_data = $this->input->get_post('order_data');
        $attrs = $this->getOrderInfo($order_data);
        if(!isset($attrs) || empty($attrs['data'])){
            $this->response(array('error' => '對不起參數錯誤,您的訂單提交失敗!','status'=>0), 200);
        }
        $table_num = $this->input->get_post('table_num');
        if(empty($table_num)){
            $this->response(array('error' => '请输入桌号!','status'=>0), 200);
        }
        $invoice_no = date('ymd').substr(time(),-5).substr(microtime(),2,5);//隨機訂單號不順序
        $data['invoice_no'] = $invoice_no;
        $data['nickname'] = '--';
        $data['phone'] = '--';
        $data['address'] = '--';
        $data['order_time'] = '--';
        $data['order_way'] = '--';
        $data['comment'] = '--';
        $data['table_num'] = $table_num;
        $data['total'] = $attrs['total'];
        $data['product_num'] = $attrs['num'];
        $data['order_status_id'] = 2;
        $data['add_time'] = time();
        $data['update_time'] = time();
        $order_id=$this->orders_mdl->add_orders($data);
        if($order_id){
            $order_product = array();
            foreach($attrs['data'] as $k=>$row){
                $order_product[$k]['order_id'] = $order_id;
                $order_product[$k]['product_id'] = $row['id'];
                $order_product[$k]['name'] = $row['title'];
                $order_product[$k]['model'] = $row['unit'];
                $order_product[$k]['color'] = $row['main_image'];
                $order_product[$k]['quantity'] = $row['num'];
                $order_product[$k]['price'] = $row['price'];
                $order_product[$k]['total'] = $row['price']*$row['num'];
                $order_product[$k]['specs'] = $row['spec'];
                $order_product[$k]['pname'] = isset($row['pname']) ? $row['pname'] : '';
                $order_product[$k]['pos_id'] = $row['pos_id'];
                $order_product[$k]['attrs'] = isset($row['attrArr']) && count($row['attrArr']) > 0 ? serialize($row['attrArr']) : null;
            }
            $this->ordersproduct_mdl->addOrdersproduct($order_product);
            $order['msg'] = '你的訂單已成功提交，訂單編號為：'.$invoice_no.'，我們會盡快聯絡你確認訂單，謝謝。';
            $order['table_num'] = $data['table_num'];
            $path1 = "api/orders/yprint?order_id=".$order_id;
            $path2 = "api/account/posprint?order_id=".$order_id;
            $result = curl_get($path1,$path2);
            if(isset($result)){
                $this->response(array('data'=>$order,"status"=>1), 200);
            }

        }else{
            $this->response(array('error' => '對不起,訂單載入失敗!','status'=>0), 200);
        }
    }
    private function getOrderInfo($getOrder){
        $orderArray = htmlspecialchars_decode($getOrder);
        $cart_data = json_decode($orderArray,true);
        if(!isset($cart_data) || empty($cart_data)){
            $this->response(array('error' => '參數錯誤!','status'=>0), 200);
        }
        $base = array();
        $num = 0;
        $total = 0;
        if(!empty($cart_data)) {
            foreach ($cart_data as $k => $cart) {
                $result = $this->products_mdl->get_products_by_unique_url(array('id' => $cart['id']));
                if (isset($cart) && is_array($cart)) {
                    $base[$k]['id'] = $result['id'];
                    $base[$k]['pname'] = $result['title'];
                    $base[$k]['unit'] = $result['unit'];
                    $base[$k]['pos_id'] = $result['pos_id'];
                    if (!empty($result['main_image'])) {
                        $base[$k]['main_image'] = base_url($result['main_image']);
                    } else {
                        $base[$k]['main_image'] = base_url('themes/front/img/no-image.png');
                    }
                    $spec_arr = explode('_', $cart['key']);
                    sort($spec_arr);
                    $spec_key = implode("_", $spec_arr);
                    $arrePrice = $this->products_mdl->getSpecItemPrice($spec_key);
                    if ($arrePrice != 0) {
                        $result['price'] += $arrePrice;
                    }
                    $name = $this->products_mdl->getSpecItemName($spec_key);
                    $base[$k]['title'] = $result['title'] . " " . $name;
                    $base[$k]['spec'] = $spec_key;
                    $base[$k]['num'] = (int)$cart['num'];
                    $base[$k]['price'] = format_free($result['price']);
                    $num += (int)$cart['num'];
                    $base[$k]['attrArr'] = array();
                    if (isset($cart['attrs']) && !empty($cart['attrs'])) {
                        $attrArr = $cart['attrs'];
                        $attrItems = $this->specs_mdl->_get_itemsBYIds(array_keys($attrArr), '');
                        if ($attrItems) {
                            foreach ($attrItems as $attr) {
                                $attr['num'] = $attrArr[$attr['id']];
                                $base[$k]['attrArr'][] = $attr;
                                $result['price'] += $attrArr[$attr['id']] > 0 ? $attrArr[$attr['id']] * $attr['price'] : 0;
                            }
                        }
                    }
                    $total += $result['price'] * $cart['num'];

                } else {
                    $base[$k]['attrArr'] = array();
                    $base[$k]['num'] = (int)$cart['num'];
                    $num += $cart['num'];
                    $total += $result['price'] * $cart['num'];
                    $base[$k]['spec'] = 0;
                }
            }
        }
        return array('num'=>$num,'total'=>format_free($total),'data'=>$base);
    }
}